package com.example.flutterapptest2

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.os.Environment
import android.util.Base64
import android.util.Log
import android.widget.Toast
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class MethodChannelTest(val context: Context, val messenger: BinaryMessenger?, val name: String?){
    private val PATH = "${Environment.getExternalStorageDirectory()}/地理数据采集";
    private val PERMI = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    );

    private lateinit var methodCall: MethodCall

    private lateinit var mResult:MethodChannel.Result

    fun getBattery() {
        MethodChannel(messenger, name).setMethodCallHandler { call, result ->
            when (call.method) {
                "getPlatformVersion" -> {
                    result.success(getBatteryLevel())
                    Toast.makeText(context, "传递成功, ${call.arguments}", Toast.LENGTH_SHORT).show();
                }
                "startActivity" -> {
                    context.startActivity(Intent(context, TestActivity().javaClass))
                }
                "downloading" -> {
                    methodCall = call
                    mResult = result;
                    if (EasyPermissions.hasPermissions(context,PERMI[0], PERMI[1])) {
                        loadingFile()
                    } else {
                        EasyPermissions.requestPermissions(context as Activity, "请授予权限", 0, PERMI[0], PERMI[1])
                    }
                }
            }
        }
    }

    @AfterPermissionGranted(0)
    fun loadingFile() {
        val map = methodCall.arguments as Map<*, *>
        val fileName = map["fileName"] as String
        val content = map["shapefile"] as String
        val i = base64ToFile(PATH, content, fileName)
        if (i == 0) {
            mResult.error("保存失败", "文件保存失败", "文件下载保存时出错")
        } else {
            mResult.success("文件保存成功: $PATH/$fileName")
        }
    }


    private fun getBatteryLevel(): Int {
        val batteryLevel: Int
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val batteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
        } else {
            val intent = ContextWrapper(context).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
            batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
        }
        return batteryLevel
    }


    //BASE64解码成File文件
    fun base64ToFile(destPath: String, base64: String?, fileName: String) : Int{
        var file: File? = null
        //创建文件目录
        val dir = File(destPath)
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs()
        }
        var bos: BufferedOutputStream? = null
        var fos: java.io.FileOutputStream? = null
        try {
            val bytes: ByteArray = Base64.decode(base64, Base64.DEFAULT);
            file = File("$destPath/$fileName")
            if (!file.exists()) {
                file.createNewFile()
            }
            fos = FileOutputStream(file)
            bos = BufferedOutputStream(fos)
            bos.write(bytes)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (bos != null) {
                try {
                    bos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            if (fos != null) {
                try {
                    fos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }

        return if (file?.exists()!! && file.length() != 0L) {
            1;
        } else {
            0;
        }
    }
}